package com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.PermissionChecker
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.alivc.live.baselive_push.ui.PushConfigActivity
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityShedForRaceListBinding
import com.gexiaobao.pigeon.ui.activity.LoginActivity
import com.gexiaobao.pigeon.ui.adapter.ShedOrgMatchAdapter
import com.gexiaobao.pigeon.viewmodel.ShedPigeonViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.lifecycle.KtxActivityManger
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2024/6/11 16:32
 * @Describe    : 公棚下比赛列表
 */
class ActivityShedRace : BaseActivity<ShedPigeonViewModel, ActivityShedForRaceListBinding>() {

    private lateinit var mAdapter: ShedOrgMatchAdapter
    private lateinit var loadsir: LoadService<Any>

    private var mOrgId = ""
    private var mFollowStatus = 0
    private var mPair = 0//是否有配对权限
    private var mVideo = 0//是否有上传探视视频权限

    private var mNoPermissionIndex = 0
    private val PERMISSION_REQUEST_CODE = 1
    private val permissionManifest = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.BLUETOOTH,
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.INTERNET,
        Manifest.permission.BLUETOOTH_CONNECT,
    )

    private val permissionManifest33 = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.BLUETOOTH,
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.READ_MEDIA_IMAGES,
        Manifest.permission.READ_MEDIA_VIDEO,
        Manifest.permission.READ_MEDIA_AUDIO,
        Manifest.permission.INTERNET,
        Manifest.permission.BLUETOOTH_CONNECT,
    )

    private val noPermissionTip = intArrayOf(
        R.string.no_camera_permission,
        R.string.no_record_bluetooth_permission,
        R.string.no_record_audio_permission,
        R.string.no_read_phone_state_permission,
        R.string.no_write_external_storage_permission,
        R.string.no_read_external_storage_permission,
        R.string.no_internet_permission,
        R.string.no_record_bluetooth_permission,
    )

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = "往期赛事"
        mDatabind.includeBar.tvRightMenu.text = "退出"
        val type = intent.getIntExtra("type", 0)
        if (type == 1) {
            mDatabind.includeBar.ivBack.isVisible = false
            mDatabind.includeBar.tvRightMenu.isVisible = true
            mOrgId = KvUtils.decodeInt(Constant.ORG_ID).toString()
        } else {//用户进入
            mDatabind.includeBar.ivBack.isVisible = true
            mDatabind.includeBar.tvRightMenu.isVisible = false
            mOrgId = intent.getIntExtra("orgId", 0).toString()
            mPair = intent.getIntExtra("pair", 0)
            mVideo = intent.getIntExtra("video", 0)
        }
        checkPermissions()
        mAdapter = ShedOrgMatchAdapter(mPair, mVideo)
        mFollowStatus = intent.getIntExtra("followStatus", 0)
        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(this, 5f)))
            it.initFooter {
                //触发加载更多时请求数据
                mViewModel.getOrgRaceListApp(false, mOrgId)
            }
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getOrgRaceListApp(true, mOrgId)
        }

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.getOrgRaceListApp(true, mOrgId)
        }

        loadsir.showLoading()
        mViewModel.getOrgRaceListApp(true, mOrgId)

        mAdapter.addChildClickViewIds(R.id.tvItemShedPair, R.id.tvItemShedUpLoadVideo, R.id.tvItemScan, R.id.tvItemTurnLiving)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tvItemTurnLiving -> {
                    val raceId = mAdapter.data[position].id
                    val pushUrl = Constant.LIVE_URL + raceId + "/" + mOrgId + "/" + "livestream"
                    startActivity<PushConfigActivity>("pushUrl" to pushUrl)
                }

                R.id.tvItemScan -> startActivity<ActivityVisitationDataPrinting>("raceId" to mAdapter.data[position].id)
                R.id.tvItemShedPair -> startActivity<ActivityCollectPigeons>("raceId" to mAdapter.data[position].id)
                R.id.tvItemShedUpLoadVideo -> startActivity<ActivityShedPigeonVideo>(
                    "raceId" to mAdapter.data[position].id,
                    "orgId" to mOrgId
                )
            }
        }
    }

    private fun checkPermissions() {
        if (!permissionCheck()) {
            if (Build.VERSION.SDK_INT >= 23) {
                ActivityCompat.requestPermissions(this, getPermissions(), PERMISSION_REQUEST_CODE)
            } else {
                showNoPermissionTip(getString(noPermissionTip[mNoPermissionIndex]))
                finish()
            }
        }
    }

    private fun showNoPermissionTip(tip: String) {
        Toast.makeText(this, tip, Toast.LENGTH_LONG).show()
    }

    @SuppressLint("WrongConstant")
    private fun permissionCheck(): Boolean {
        var permissionCheck = PackageManager.PERMISSION_GRANTED
        var permission: String
        for (i in getPermissions().indices) {
            permission = getPermissions()[i]
            mNoPermissionIndex = i
            if (PermissionChecker.checkSelfPermission(this, permission)
                != PackageManager.PERMISSION_GRANTED
            ) {
                permissionCheck = PackageManager.PERMISSION_DENIED
            }
        }
        return permissionCheck == PackageManager.PERMISSION_GRANTED
    }

    private fun getPermissions(): Array<String> {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
            return permissionManifest
        }
        return permissionManifest33
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeBar.tvRightMenu, mDatabind.includeBar.ivBack) {
            when (it) {
                mDatabind.includeBar.ivBack -> finish()
                mDatabind.includeBar.tvRightMenu -> mViewModel.loginOut()
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 退出 */
        mViewModel.logOutResult.observe(this) {
            if (it.isSuccess) {
                CacheUtil.setIsLogin(false)
                KtxActivityManger.finishAllActivity()
                startActivity<LoginActivity>()
                //带点渐变动画
                this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取组织下赛事 */
        mViewModel.orgMatchResult.observe(this) {
            if (it.isSuccess) {
                loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
            } else {
                RxToast.showToast(it.errMessage)
            }
        }
    }
}

